
package Servlets;

import Entidades.Usuario;
import iBatis.Persistencia;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *  LuxarJSP
 *      - Javier Ruiz Hidalgo
 *      - Miguel Alejandro Esteban Ordoñez
 */

/**
 *  Descripción de la Clase:
 *      - Servlet que trata la edición del Avatar del Usuario
 */

@WebServlet(name="ServletNuevoAvatar", urlPatterns={"/ServletNuevoAvatar"})
public class ServletNuevoAvatar extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, FileUploadException, Exception {
        HttpSession session = request.getSession(false);
        if (session != null) {
            //Empezamos leyendo todos los parametros enviados por request debido a la encriptacion multipart/form-data
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = upload.parseRequest(request);
            String imagen = null;

            for (Object item : items) {
                FileItem uploaded = (FileItem) item;
                if (!uploaded.isFormField()) {
                    if (uploaded.getName() != null && soloImagenes(uploaded.getContentType()) && uploaded.getSize() < (1024 * 1024)){
                        String ruta = request.getRealPath("/avatar") + "/";
                        File fileServer = new File(ruta + new Date().getTime() + uploaded.getName());
                        uploaded.write(fileServer);
                        imagen = fileServer.getName();
                    }
                } else {
                    String name = uploaded.getFieldName();
                    String value = uploaded.getString();
                    session.setAttribute(name, value);
                }
            }

            if (session.getAttribute("envio") != null) {
                if (imagen != null) {
                    String imgAntigua = Persistencia.obtieneAvatar((String)session.getAttribute("usuarioIdentificado"));

                    //Borramos el antiguo Avatar, si lo hubiera
                    if(imgAntigua != null){
                        eliminaImagen(request.getRealPath("/") + imgAntigua);
                    }

                    //Instanciamos un usuario
                    Usuario usuario = new Usuario();
                    usuario.setAvatar("avatar/" + imagen);
                    usuario.setUsuario((String)session.getAttribute("usuarioIdentificado"));

                    //Actualizamos la BD
                    Persistencia.actualizaAvatar(usuario);
                }

                String url = "/index.jsp";
                ServletContext sc = getServletContext();
                RequestDispatcher rd = sc.getRequestDispatcher(url);
                rd.forward(request, response);
            }
        }
    }

    private boolean soloImagenes(String tipo) {
        boolean confirm = false;

        if (tipo.equals("image/gif") || tipo.equals("image/jpeg") || tipo.equals("image/pjpeg")) {
            confirm = true;
        }

        return confirm;
    }

    private void eliminaImagen(String ruta){
        File file = new File(ruta);
        file.delete();
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(ServletNuevoAvatar.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(ServletNuevoAvatar.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(ServletNuevoAvatar.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(ServletNuevoAvatar.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
